package com.magicode.screen.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppConfig;
import com.magicode.screen.AppContext;
import com.magicode.screen.R;
import com.magicode.screen.api.ApiHttpClient;
import com.magicode.screen.api.remote.MgcApi;
import com.magicode.screen.bean.Constants;
import com.magicode.screen.bean.User;
import com.magicode.screen.react.activity.MainTabReactActivity;
import com.magicode.screen.util.CyptoUtils;
import com.magicode.screen.util.UIHelper;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.kymjs.kjframe.http.HttpConfig;

import java.util.ArrayList;


/**
 * app欢迎页
 * Created by dell on 2016/5/28.
 */
public class WelcomeActivity extends Activity implements View.OnClickListener,ViewPager.OnPageChangeListener {
    //定义ViewPager对象
    private ViewPager viewPager;

    //定义ViewPager适配器
    private ViewPagerAdapter vpAdapter;

    //定义一个ArrayList来存放View
    private ArrayList<View> views;

    //引导图片资源
    private static final int[] pics = {R.drawable.icon_weclome1,R.drawable.icon_weclome2,R.drawable.icon_weclome3};
    private Button bt_home;//在ViewPager的最后一个页面设置一个按钮，用于点击跳转到MainActivity
    //底部小点的图片
    private ImageView[] points;
    //判断是否第一次登陆
    private boolean isFirstIn = true;
    //记录当前选中位置
    private int currentIndex;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 获取sharedPrefernces对象判断，是不是第一次启动软件
        SharedPreferences setting = getSharedPreferences("SHARE_APP_TAG", 0);
        Boolean user_first = setting.getBoolean("FIRST",true);
        if(user_first){//第一次
            setting.edit().putBoolean("FIRST", false).commit();
            setContentView(R.layout.activity_guide);
            initView();
            initData();
        }else{
        setContentView(R.layout.activity_welcome);
        //new Handler().postDelayed(r, 100);
            new Handler().post(r);
           // new Handler().postAtFrontOfQueue(r);
        }


/*        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcome);
//        if(AppContext.shouldAskPermission()){
//            AppContext.verifyPermissions(this);
//        }
        // 延迟几秒，然后跳转到登录页面
            new Handler().postDelayed(r, 3000);*/
    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            //           handledefaultLogin();//默认登录
            UIHelper.showMainTabActivity(getApplicationContext());
//            UIHelper.showMainActivity(getApplicationContext());
        }
    };
    private void handledefaultLogin() {
        if(null!= AppContext.getInstance()) {
            String userId= AppContext.getInstance().getLoginUid();
            String loginName= AppContext.getInstance().getProperty("user.loginName");
            String password= CyptoUtils.decode("MagicodeApplication", AppContext.getInstance().getProperty("user.password"));
            if(null!=userId &&!"".equals(userId) && null!=loginName &&!"".equals(loginName) &&
                    null!=password &&!"".equals(password)){
                MgcApi.defaultLogin(loginName, password, mHandler);
            } else{
                handleLoginSuccess();
            }
        }
    }
    private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                AsyncHttpClient client = ApiHttpClient.getHttpClient();
                HttpContext httpContext = client.getHttpContext();
                CookieStore cookies = (CookieStore) httpContext
                        .getAttribute(ClientContext.COOKIE_STORE);
                if (cookies != null) {
                    String tmpcookies = "";
                    for (Cookie c : cookies.getCookies()) {
                        tmpcookies += (c.getName() + "=" + c.getValue()) + ";";
                    }
                    AppContext.getInstance().setProperty(AppConfig.CONF_COOKIE,
                            tmpcookies);
                    ApiHttpClient.setCookie(ApiHttpClient.getCookie(AppContext
                            .getInstance()));
                    HttpConfig.sCookie = tmpcookies;
                }
                ObjectMapper mapper = new ObjectMapper();
                User user = mapper.readValue(arg2, User.class);

                if (user.isOk()) {
                    // 保存登录信息
                    AppContext.getInstance().saveUserInfo(user);
                } else {
                    AppContext.getInstance().cleanLoginInfo();
                }
                handleLoginSuccess();
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
            }
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                              Throwable arg3) {
            handleLoginSuccess();
        }
    };

    private void handleLoginSuccess() {
        Intent data = new Intent();
        setResult(RESULT_OK, data);
        this.sendBroadcast(new Intent(Constants.INTENT_ACTION_USER_CHANGE));
        finish();
        Intent intent=new Intent(this,MainTabReactActivity.class);  //方法1
        startActivity(intent);
        overridePendingTransition(R.anim.anim_right_get_into, R.anim.anim_left_sign_out);
    }


    public void initView() {
        //实例化ArrayList对象
        views = new ArrayList<View>();

        //实例化ViewPager
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        //实例化ViewPager适配器
        vpAdapter = new ViewPagerAdapter(views);
    }
    //    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        doNext(requestCode, grantResults);
//    }
//
//    private void doNext(int requestCode, int[] grantResults) {
//        if (requestCode == 1) {
//            if (grantResults.length>0) {
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                } else {
//                    Toast.makeText(this, "请在应用管理中打开“相机”访问权限！", Toast.LENGTH_LONG).show();
//                }
//            }
//        }
//    }

    public void initData() {
        //定义一个布局并设置参数
        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT);

        //初始化引导图片列表
        for(int i=0; i<pics.length; i++) {
            ImageView iv = new ImageView(this);
            iv.setLayoutParams(mParams);
            iv.setImageResource(pics[i]);
            views.add(iv);
        }

        //设置数据
        try{
            viewPager.setAdapter(vpAdapter);
        }catch (Exception e){
            e.printStackTrace();
        }

        //设置监听
        viewPager.setOnPageChangeListener(this);
        bt_home= (Button)findViewById(R.id.to_Main);
        bt_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(WelcomeActivity.this,MainTabReactActivity.class);
                startActivity(intent);
                finish();
            }
        });

        //初始化底部小点
        initPoint();
    }
    /**
     * 初始化底部小点
     */
    private void initPoint(){
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll);

        points = new ImageView[pics.length];

        //循环取得小点图片
        for (int i = 0; i < pics.length; i++) {
            //得到一个LinearLayout下面的每一个子元素
            points[i] = (ImageView) linearLayout.getChildAt(i);
            //默认都设为灰色
            points[i].setEnabled(true);
            //给每个小点设置监听
            points[i].setOnClickListener(this);
            //设置位置tag，方便取出与当前位置对应
            points[i].setTag(i);
        }

        //设置当面默认的位置
        currentIndex = 0;
        //设置为白色，即选中状态
        points[currentIndex].setEnabled(false);
    }

    /**
     * 通过点击事件来切换当前的页面
     */
    @Override
    public void onClick(View v) {
        int position = (Integer)v.getTag();
        setCurView(position);
        setCurDot(position);
    }

    protected boolean hasActionBar() {
        return false;
    }

    /**
     * 当当前页面被滑动时调用
     */

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    /**
     * 当新的页面被选中时调用
     */

    @Override
    public void onPageSelected(int position) {
        //设置底部小点选中状态
        setCurDot(position);
    }

    /**
     * 当滑动状态改变时调用
     */
    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
    /**
     * 设置当前页面的位置
     */
    private void setCurView(int position){
        if (position < 0 || position >= pics.length) {
            return;
        }
        viewPager.setCurrentItem(position);
    }

    /**
     * 设置当前的小点的位置
     */
    private void setCurDot(int positon){
        if (positon < 0 || positon > pics.length - 1 || currentIndex == positon) {
            return;
        }
        points[positon].setEnabled(false);
        points[currentIndex].setEnabled(true);

        currentIndex = positon;
    }
}
